package DBConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

import com.buaa.utils.BaseUtil;

//import com.sun.org.apache.xerces.internal.parsers.DOMParser;

/**
 * 读取数据库的类
 * @author cjl
 */

public class DB {
	private String jdbcDriver;
	@SuppressWarnings("unused")
	private String dbName;
	private String urlRoot;
	private String username;
	private String password;
	
	public Statement sm = null;
	private Connection conn = null;

	public DB(){
		try
		{
			Properties p=BaseUtil.getProperties();						
			jdbcDriver = p.getProperty("jdbc.driver");				
			dbName = p.getProperty("jdbc.db");			
			urlRoot = p.getProperty("jdbc.url");				
			username = p.getProperty("jdbc.username");			
            password = p.getProperty("jdbc.password");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public DB(String db){
		try
		{			
			Properties p=BaseUtil.getProperties();						
		    jdbcDriver = p.getProperty("jdbc.driver");				
		    dbName = p.getProperty(db);			
		    urlRoot = p.getProperty("jdbc.url");				
		    username = p.getProperty("jdbc.username");			
            password = p.getProperty("jdbc.password");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	//建立数据库链接
	public void ConnectDB(){
		try {
			Class.forName(jdbcDriver).newInstance();
			// sql server
			//conn = DriverManager.getConnection(urlRoot + ";databaseName=" + dbName + ";user=" + username + ";password=" + password);
			// mysql
			conn = DriverManager.getConnection(urlRoot, username, password);
			sm = conn.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//关闭数据库链接
	public void CloseDB(){
		try{
			if(sm != null){
				sm.close();
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
